package com.xwtech.cring.admin.controller;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.xwtech.cms.data.AbstractDataAdapter;
import com.xwtech.cms.data.db.JdbcTransaction;
import com.xwtech.cring.admin.pub.AdminUserRetConst;
import com.xwtech.framework.pub.result.ResultInfo;
import com.xwtech.framework.pub.result.ResultInfos;
import com.xwtech.framework.pub.web.RequestNameConstants;

/**
 * 后台管理员菜单管理Controller
 * @author sunjs
 */
public class AdminUserMenuController extends MultiActionController {

	private static final Log log = LogFactory
			.getLog(AdminUserMenuController.class);
	
	/**
	 * insert菜单
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView insertMenu(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		/*
			1.	增加url(frame_url)
			2.	增加子菜单(frame_submenu)
		*/
		
		HashMap map = updateDBfromXml(request);
		return new ModelAndView("/cring/jsp/admin/information.jsp",
				RequestNameConstants.INFORMATION, map);
	}

	/**
	 * 修改菜单
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView updateMenu(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		/*
			1.	修改url(frame_url)
			2.	修改子菜单(frame_submenu)
		*/
		
		HashMap map = updateDBfromXml(request);
		return new ModelAndView("/cring/jsp/admin/information.jsp",
				RequestNameConstants.INFORMATION, map);
	}
	
	/**
	 * 删除菜单
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView removeMenu(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		HashMap map = removeMenufromXml(request);
		return new ModelAndView("/cring/jsp/admin/information.jsp",
				RequestNameConstants.INFORMATION, map);
	}
	
	/**
	 * <简述>删除菜单
	 * <业务流程>
	 * 1.	查看当前菜单有没有子菜单
	 * 2.	如果有子菜单，则不可以删除；如没有子菜单，可以进行删除操作
	 * 2.1.	将菜单url置为无效(frame_url)
	 * 2.2.	将菜单置为无效(frame_submenu)
	 * 2.3.	将菜单对应角色置为无效(frame_role)
	 * 2.4.	将权限菜单表数据删除(frame_role_submenu)
	 * 2.5.	将角色权限对应表相关数据删除(sys_role_right)
	 * @param request
	 * @return
	 * @throws SQLException 
	 */
	private HashMap removeMenufromXml(HttpServletRequest request) throws SQLException {
		String adapter = request.getParameter("_adapter");
		String url = request.getParameter("_url");

		String hasSubMenuSql = "/admin/AdminUserMenu_hasSubmenu.xml";
		String removeUrlSql = "/admin/AdminUserUrl_remove.xml";
		String removeMenuSql = "/admin/AdminUserMenu_remove.xml";
		String removeRoleSql = "/admin/AdminUserRole_remove.xml";
		String deleteRoleMenuSql = "/admin/AdminUserRoleMenu_delete.xml";
		String deleteSysRoleRightSql = "/admin/AdminUserSysRoleRight_delete_by_role_id.xml";
		
		ResultInfos resultInfos = new ResultInfos();
		AbstractDataAdapter ada = AbstractDataAdapter.getDataAdapter(request
				.getSession().getServletContext(), adapter);
		
		
		//1.	查看当前菜单有没有子菜单
		List retHasSubmenuList = ada.list(hasSubMenuSql, request);
		
		//2.	如果有子菜单，则不可以删除；如没有子菜单，可以进行删除操作
		if (null != retHasSubmenuList && retHasSubmenuList.size() > 0) {
			resultInfos.add(new ResultInfo(AdminUserRetConst.MENU_OP_FAILED));
			log.debug("该菜单还有子菜单，不能删除！");
		} else {
			int ret = -1;
			JdbcTransaction trans = ada.getTransaction();
			try {
				//2.1.	将菜单url置为无效
				ret = trans.update(removeUrlSql, request);
				
				//2.2.	将菜单置为无效
				ret = trans.update(removeMenuSql, request);
				
				//2.3.	将菜单对应角色置为无效(frame_role)
				ret = trans.update(removeRoleSql, request);
				
				//2.4.	将权限菜单表数据删除(frame_role_submenu)
				ret = trans.update(deleteRoleMenuSql, request);
				
				//2.5.	将角色权限对应表相关数据删除(sys_role_right)
				ret = trans.update(deleteSysRoleRightSql, request);
				
				trans.commit();
			} catch (Exception e) {
				log.error("数据库操作时出错！", e);
				trans.rollback();
				ret = -1;
			}
			
			if (ret < 0) {
				resultInfos.add(new ResultInfo(AdminUserRetConst.MENU_OP_FAILED));
				log.debug("数据库操作失败...");
			} else {
				resultInfos.add(new ResultInfo(AdminUserRetConst.MENU_OP_SUCCESS));
				log.debug("数据库操作成功...");
			}
		}
		
		resultInfos.setGotoUrl(url);
		
		HashMap map = new HashMap();
		map.put(RequestNameConstants.RESULTINFOS, resultInfos);
		return map;
	}

	private HashMap updateDBfromXml(HttpServletRequest request)
			throws SQLException {
		
		String adapter = request.getParameter("_adapter");
		String url = request.getParameter("_url");
		String sqlXml = request.getParameter("_sql");
		
		// 对得到的xml路径字符串分组
		String[] xmlString = sqlXml.split(",");
		AbstractDataAdapter ada = AbstractDataAdapter.getDataAdapter(request
				.getSession().getServletContext(), adapter);
		int ret = -1;
		log.debug("共有sql-xml配置文件" + xmlString.length + "个");
		if (xmlString.length > 1) {
			log.debug("需要进行事务处理...");
			JdbcTransaction transaction = ada.getTransaction();
			try {
				for (int i = 0; i < xmlString.length; i++) {
					ret = transaction.update(xmlString[i], request);
				}
				transaction.commit();
			} catch (Exception e) {
				log.error("数据库操作时出错！", e);
				transaction.rollback();
				ret = -1;
			}
		} else {
			ret = ada.update(sqlXml, request);
		}
			
		ResultInfos resultInfos = new ResultInfos();
		if (ret < 0) {
			resultInfos.add(new ResultInfo(AdminUserRetConst.MENU_OP_FAILED));
			log.debug("数据库操作失败...");
		} else {
			resultInfos.add(new ResultInfo(AdminUserRetConst.MENU_OP_SUCCESS));
			log.debug("数据库操作成功...");
		}
		resultInfos.setGotoUrl(url);
		
		HashMap map = new HashMap();
		map.put(RequestNameConstants.RESULTINFOS, resultInfos);
		
		return map;
	}

}
